package net.caixiaomi.info;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.internal.BottomNavigationMenuView;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSONObject;

import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.permissions.Permission;
import net.caixiaomi.info.base.permissions.RxPermissions;
import net.caixiaomi.info.helper.BottomNavigationViewHelper;
import net.caixiaomi.info.life.DownLoadPresenter;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.QueryUserNoticeModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.login.LoginActivity;
import net.caixiaomi.info.ui.main.DiscoveryFragment;
import net.caixiaomi.info.ui.main.FindFragment;
import net.caixiaomi.info.ui.main.HomeFragment;
import net.caixiaomi.info.ui.main.MatchFragment;
import net.caixiaomi.info.ui.main.UserFragment;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.EventWhat;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import icepick.State;
import io.reactivex.functions.Consumer;
import retrofit2.Call;

public class MainActivity extends BaseActivity {

    @BindView(R.id.main_layout_tab0)
    RelativeLayout tab0;
    @BindView(R.id.main_layout_tab0_img)
    ImageView img0;

    @BindView(R.id.main_layout_tab1)
    RelativeLayout tab1;
    @BindView(R.id.main_layout_tab1_img)
    ImageView img1;

    @BindView(R.id.main_layout_tab2)
    RelativeLayout tab2;
    @BindView(R.id.main_layout_tab2_img)
    ImageView img2;

    @BindView(R.id.main_layout_tab3)
    RelativeLayout tab3;
    @BindView(R.id.main_layout_tab3_img)
    ImageView img3;

    @BindView(R.id.main_tab_point)
    View mTabPoint;


    @OnClick(R.id.main_layout_tab0)
    void toTab0() {
        setSelection(0);
    }

    @OnClick(R.id.main_layout_tab1)
    void toTab1() {
        setSelection(1);
    }

    @OnClick(R.id.main_layout_tab2)
    void toTab2() {
        setSelection(2);
    }

    @OnClick(R.id.main_layout_tab3)
    void toTab3() {
        String token = CommonApp.getToken();
        if (TextUtils.isEmpty(token)) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }
        setSelection(3);
    }

    @Nullable
    public static Fragment getFragmentByTag(@NonNull FragmentManager fragmentManager, @NonNull String tag) {
        return fragmentManager.findFragmentByTag(tag);
    }

    @Nullable
    public static Fragment getVisibleFragment(@NonNull FragmentManager manager) {
        @SuppressLint("RestrictedApi") List<Fragment> fragments = manager.getFragments();
        if (fragments != null && !fragments.isEmpty()) {
            for (Fragment fragment : fragments) {
                if (fragment != null && fragment.isVisible()) {
                    return fragment;
                }
            }
        }
        return null;
    }

    @Override
    protected int layout() {
        return R.layout.act_main;
    }

    private FragmentManager fragmentManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        fragmentManager=getSupportFragmentManager();
        CommonApp.mScreenWidth=metrics.widthPixels;
        CommonApp.mScreenHeight=metrics.heightPixels;
        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.container, HomeFragment.newInstance(), HomeFragment.TAG)
                    .commit();
        }

//        setSelection(0);
        clearTab();
        img0.setBackgroundResource(R.drawable.main_tab_home);
        addPointView();

        RxPermissions mRxPermissions = new RxPermissions(this);
        mRxPermissions
                .requestEach(
                        Manifest.permission.READ_PHONE_STATE, Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                        }
                    }
                });

        DownLoadPresenter presenter=new DownLoadPresenter();
        presenter.init(this, new DownLoadPresenter.callback() {
            @Override
            public void getStatus(String type, String message) {

            }
        });
    }

    private void addPointView() {
        try {
            boolean messageNotice = CommonApp.STORE.getBoolean(Constants.KEY_MESSAGE_NOTICE, false);
            boolean bonusNotice = CommonApp.STORE.getBoolean(Constants.KEY_BONUS_NOTICE, false);
            mTabPoint.setVisibility(CommonApp.STORE.getBoolean(Constants.KEY_DEAL_VERSION, false) && (messageNotice || bonusNotice) ? View.VISIBLE : View.GONE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onShowHideFragment(@NonNull FragmentManager fragmentManager, @NonNull Fragment toShow, @NonNull Fragment toHide) {
        fragmentManager
                .beginTransaction()
                .hide(toHide)
                .show(toShow)
                .commit();
    }

    public void onAddAndHide(@NonNull FragmentManager fragmentManager, @NonNull Fragment toAdd, @NonNull Fragment toHide) {
        fragmentManager
                .beginTransaction()
                .hide(toHide)
                .add(R.id.container, toAdd, toAdd.getClass().getSimpleName())
                .commit();
    }

    private void queryUserNotice() {
        JSONObject params = new JSONObject();
        params.put("str", String.valueOf(System.currentTimeMillis()));
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<QueryUserNoticeModel>> baseCallModelCall = requestService.queryUserNotice(params);
        baseCallModelCall.enqueue(new ResponseCallback<BaseCallModel<QueryUserNoticeModel>>() {
            @Override
            public void onSuccess(BaseCallModel<QueryUserNoticeModel> data) {
                QueryUserNoticeModel model = data.data;
                boolean oldMessageNotice = CommonApp.STORE.getBoolean(Constants.KEY_MESSAGE_NOTICE, false);
                boolean oldBonusNotice = CommonApp.STORE.getBoolean(Constants.KEY_BONUS_NOTICE, false);
                boolean newMessageNotice = model.getMessageNotice() != 0;
                boolean newBonusNotice = model.getBonusNotice() != 0;
                CommonApp.STORE.set(Constants.KEY_MESSAGE_NOTICE, newMessageNotice);
                CommonApp.STORE.set(Constants.KEY_BONUS_NOTICE, newBonusNotice);
                if (oldMessageNotice != newMessageNotice || oldBonusNotice != newBonusNotice) {
                    EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_NEW_NOTICE_POINT));
                }
            }

            @Override
            public void onFail(ResponseError error) {
            }

            @Override
            public void onError() {
            }
        });
    }

    @Override
    public void onPostEvent(CommonEvent event) {
        try {
            switch (event.getWhat()) {
                case EventWhat.EVENT_LOGIN_OUT_RETURN_HOME:
                    setSelection(0);
                    break;
                case EventWhat.EVENT_NEW_NOTICE_POINT:
                case EventWhat.EVENT_APP_BACKGROUND_UPDATE_DEAL_VERSION:
                    boolean messageNotice = CommonApp.STORE.getBoolean(Constants.KEY_MESSAGE_NOTICE, false);
                    boolean bonusNotice = CommonApp.STORE.getBoolean(Constants.KEY_BONUS_NOTICE, false);
                    mTabPoint.setVisibility(CommonApp.STORE.getBoolean(Constants.KEY_DEAL_VERSION, false) && (messageNotice || bonusNotice) ? View.VISIBLE : View.GONE);
                    break;
                case EventWhat.EVENT_LOGIN:
                    queryUserNotice();
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setSelection(int position){
        try {
//            FragmentManager fragmentManager=getSupportFragmentManager();
            Fragment currentVisible = getVisibleFragment(fragmentManager);
            HomeFragment homeFragment = (HomeFragment) getFragmentByTag(fragmentManager, HomeFragment.TAG);
            MatchFragment lotteryFragment = (MatchFragment) getFragmentByTag(fragmentManager, MatchFragment.TAG);
            UserFragment userFragment = (UserFragment) getFragmentByTag(fragmentManager, UserFragment.TAG);
            DiscoveryFragment findFragment = (DiscoveryFragment) getFragmentByTag(fragmentManager, DiscoveryFragment.TAG);
            clearTab();
            switch (position){
                case 0:
                    if (homeFragment == null) {
                        onAddAndHide(fragmentManager, HomeFragment.newInstance(), currentVisible);
                    } else {
                        onShowHideFragment(fragmentManager, homeFragment, currentVisible);
                    }
                    img0.setBackgroundResource(R.drawable.main_tab_home);
                    break;
                case 1:
                    if (lotteryFragment == null) {
                        onAddAndHide(fragmentManager, MatchFragment.newInstance(), currentVisible);
                    } else {
                        onShowHideFragment(fragmentManager, lotteryFragment, currentVisible);
                        lotteryFragment.matchingBarSelected(0);
                    }
                    img1.setBackgroundResource(R.drawable.main_match_set);
                    break;
                case 2:
                    if (findFragment == null) {
                        onAddAndHide(fragmentManager, DiscoveryFragment.newInstance(), currentVisible);
                    } else {
                        onShowHideFragment(fragmentManager, findFragment, currentVisible);
                    }
                    img2.setBackgroundResource(R.drawable.main_tab_dis);
                    break;
                case 3:
                    if (userFragment == null) {
                        onAddAndHide(fragmentManager, UserFragment.newInstance(), currentVisible);
                    } else {
                        onShowHideFragment(fragmentManager, userFragment, currentVisible);
                    }
                    img3.setBackgroundResource(R.drawable.main_tab_min);
                    break;
            }
            if(lotteryFragment!=null){
                if(position==1){
                    lotteryFragment.setCurrentFragmentOnresume(true);
                }else{
                    lotteryFragment.setCurrentFragmentOnresume(false);
                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void clearTab(){
        img0.setBackgroundResource(R.drawable.main_tab_home_nor);
        img1.setBackgroundResource(R.drawable.main_match_nor);
        img2.setBackgroundResource(R.drawable.main_tab_dis_nor);
        img3.setBackgroundResource(R.drawable.main_tab_min_nor);
    }
}
